template <typename T>
class UnionFindSet
{
public:
    UnionFindSet()
    {
    }

    template <typename TContainer>
    UnionFindSet(const TContainer &container)
    {
        auto begin = container.begin();
        auto end = container.end();
        while (begin != end)
        {
            m[*begin] = *begin;
            ++begin;
            ++_groupCount;
        }
    }

    void insert(const T &value)
    {
        if (!m.count(value))
        {
            m[value] = value;
            ++_groupCount;
        }
    }

    bool exist(const T &value)
    {
        return m.count(value);
    }

    T find(const T &value)
    {
        if (m[value] == value)
        {
            return value;
        }
        return m[value] = find(m[value]);
    }

    void join(const T &value1, const T &value2)
    {
        if (find(value1) != find(value2))
        {
            m[find(value1)] = find(value2);
            --_groupCount;
        }
    }

    int groupCount()
    {
        return _groupCount;
    }

private:
    std::unordered_map<T, T> m;
    int _groupCount = 0;
};

class Solution
{
public:
    int minSwapsCouples(vector<int> &row)
    {
        int n = row.size() / 2;
        UnionFindSet<int> ufs;
        for (int i = 0; i < n; ++i)
        {
            ufs.insert(i);
        }
        for (int i = 0; i < n; ++i)
        {
            ufs.join(row[2 * i] / 2, row[2 * i + 1] / 2);
        }
        return n - ufs.groupCount();
    }
};